﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace ImbedLibrary
{
    public class ImageHelper
    {

        /// <summary>
        /// 转换为灰度
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static Bitmap ConvertToGayEx(Bitmap source, ref float[][] colorMatrix)
        {
            Bitmap newBitMap = null;
            Graphics g = Graphics.FromImage(source);
            ImageAttributes ia = new ImageAttributes();

            ColorMatrix cm = new ColorMatrix(colorMatrix);
            ia.SetColorMatrix(cm, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
            g.DrawImage(source, new Rectangle(0, 0, source.Width, source.Height), 0, 0, source.Width, source.Height, GraphicsUnit.Pixel, ia);
            g.Dispose();
            newBitMap = source;

            return newBitMap;
        }

        /// <summary>
        /// 灰度化
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        public static Bitmap GetImage(Image image)
        {
            float[][] colorMatrix = {
                                        new float[]{0.299f,0.299f,0.299f,0,0},
                                        new float[]{0.587f,0.587f,0.587f,0,0},
                                        new float[]{0.114f,0.114f,0.114f,0,0},
                                        new float[]{0,0,0,1,0},
                                        new float[]{0,0,0,0,1}
                                    };

            try
            {
                return ConvertToGayEx((Bitmap)image, ref colorMatrix);
            }
            catch
            {
                return new Bitmap(70, 75);
            }

        }

        //图像转换成二进制
        public static byte[] ImageToByte(Image Picture)
        {
            MemoryStream ms = new MemoryStream();
            if (Picture == null)
                return new byte[ms.Length];
            Picture.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] BPicture = new byte[ms.Length];
            BPicture = ms.GetBuffer();
            return BPicture;
        }
        //二进制转换为图像
        public static Image ByteToImage(byte[] btImage)
        {
            if (btImage.Length == 0)
                return null;
            System.IO.MemoryStream ms = null;
            try
            {
                ms = new System.IO.MemoryStream(btImage);
                return System.Drawing.Image.FromStream(ms);
            }
            catch(Exception ex) 
            {
            }
            finally
            {
                ms.Close();
            }
            return null;
        }
    }
}
